<?php
/**
 * 生成消消乐游戏二维码的控制器
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/6
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Wechat\V3_1;

use App\Http\Controllers\ApiController;
use App\Models\Coupon\CouponTicket;
use App\Models\Customer\Customer;
use App\Models\OpenWechat\Authorizer;
use App\Models\OpenWechat\ScanEvent;
use App\Services\OpenWechat\AuthorizerRepository;
use App\Services\OpenWechat\QrCode;
use App\Services\Utils\SimpleQrCode;
use Illuminate\Http\Request;


class BoomGameController extends ApiController
{
    const ROUTES = [
        'playQrCode' => 'Wechat.v3_1.BoomGame.playQrCode',
        'couponQrCode' => 'Wechat.v3_1.BoomGame.couponQrCode',
    ];

    const GAME_PATH = '/wx-games/index.html';

    /**
     * App（Pad）游戏中扫码转到手机（公众号）玩游戏
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function playQrCode(Request $request)
    {
        $customer_id = $request->get('customer_id');
        $customer = (new Customer)->find($customer_id);
            $this->checkItemExist($customer);

        $authorizer = $customer->authorizer;
            $this->checkItemExist($authorizer);

        $authorizer_repo = new AuthorizerRepository($authorizer);
            $authorizer_repo->checkIsTypeService();

        $scan_event = ScanEvent::createBoomGameEvent($customer_id);;

        $qr_code_result = $this->createWechatQrcode($authorizer, $scan_event);

        if ($request->get('type') === 'png') {
            return $this->responseImage(SimpleQrCode::toImage($qr_code_result['url']));
        } else {
            return $this->response($qr_code_result);
        }
    }

    /**
     * App（Pad）游戏完成扫码转到手机（公众号）卡包
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function couponQrCode(Request $request)
    {
        $customer_id = $request->get('customer_id');
        $customer = (new Customer)->find($customer_id);
            $this->checkItemExist($customer, 'customer id');

        $coupon_ticket = $customer
            ->couponTickets()
            ->where('code', $request->get('code'))
            ->first();
            $this->checkItemExist($coupon_ticket, 'coupon ticket');

        $authorizer = $customer->authorizer;
            $this->checkItemExist($authorizer);

        $authorizer_repo = new AuthorizerRepository($authorizer);
            $authorizer_repo->checkIsTypeService();

        $scan_event = ScanEvent::createCouponCartEvent($customer_id, $coupon_ticket->getKey());;

        $qr_code_result = $this->createWechatQrcode($authorizer, $scan_event);

        if ($request->get('type') === 'png') {
            return $this->responseImage(SimpleQrCode::toImage($qr_code_result['url']));
        } else {
            return $this->response($qr_code_result);
        }
    }

    /**
     * @param Authorizer $authorizer
     * @param ScanEvent $scan_event
     *
     * @return array
     *      ['url' => 'wx://abc', 'code_img_url' => 'https://xx.img' ]
     * @throws \Exception
     */
    private function createWechatQrcode(Authorizer $authorizer, ScanEvent $scan_event)
    {
        $qr_service = new QrCode();

        $qr_result = $qr_service::generate(
            $authorizer->authorizer_appid,
            $scan_event->getSceneValue()
        );
            $qr_service->checkQrResult($qr_result);

        $qr_result['code_img_url'] = QrCode::ticketToQrCodeUrl($authorizer->authorizer_appid, $qr_result['ticket']);

        return $qr_result;
    }
}
